<?php
namespace app\admin\logic;

use app\common\logic\Base;
use think\Db;
use think\facade\App;

class Finance extends Base {
    
    /**
     * @desc 提现列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function withdraw($params) {
        $where = [];
        if($params['orderNo']) {
            $where[] = ['uw_order_no', 'like', '%' .$params['orderNo']. '%'];
        }
    
        if($params['userName']) {
            $userId = App::model('User')
                ->where('user_phone', 'like', '%'.$params['userName'].'%')
                ->whereOr('user_email', 'like', '%'.$params['userName'].'%')
                ->value('user_id');
            if($userId) {
                $where[] = ['uw_user_id', '=', $userId];
            }
        }
    
        $list = App::model('UserWithdraw')
            ->where($where)
            ->order('uw_withdraw_id', 'desc')
            ->paginate($params['pageSize'], false, ['query' => request()->param()]);
    
        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = output_format($list['data'], 'uw');
        
            $userIds = array_unique(array_column($list, 'userId'));
            $memberIds = array_unique(array_column($list, 'memberId'));
    
            $userInfo = App::model('User')
                ->where('user_id', 'in', $userIds)
                ->column('user_phone,user_email', 'user_id');
    
            $memberInfo = App::model('AuthMember')
                ->where('am_member_id', 'in', $memberIds)
                ->column('am_username', 'am_member_id');
            
            foreach ($list as $k => $v) {
                $list[$k]['userName']   = $userInfo[$v['userId']]['user_phone'] ?: $userInfo[$v['userId']]['user_email'];
                $list[$k]['memberName'] = $memberInfo[$v['memberId']] ?: '';
    
            }
        }

        return [
            'list'         => $list,
            'params'       => $params,
            'pagination'   => $pagination
        ];
    }
    
    /**
     * @desc 银行卡列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bankCard($params) {
        $where = [];
        if($params['bankNo']) {
            $where[] = ['ubc_bank_no', '=', $params['bankNo']];
        }
        
        if($params['accountName']) {
            $where[] = ['ubc_account_name', '=', $params['accountName']];
        }
    
        if($params['bankName']) {
            $where[] = ['ubc_bank_name', '=', $params['bankName']];
        }
        
        $list = App::model('UserBankCard')
            ->where($where)
            ->order('ubc_id', 'desc')
            ->paginate($params['pageSize'], false, ['query' => request()->param()]);
        
        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = output_format($list['data'], 'ubc');
            
            $userIds = array_unique(array_column($list, 'userId'));
            $userInfo = App::model('User')
                ->where('user_id', 'in', $userIds)
                ->column('user_phone,user_email', 'user_id');
            
            foreach ($list as $k => $v) {
                $list[$k]['userName'] = $userInfo[$v['userId']]['user_phone'] ?: $userInfo[$v['userId']]['user_email'];
            }
        }
       
        return [
            'list'         => $list,
            'params'       => $params,
            'pagination'   => $pagination
        ];
    }
    
    
    /**
     * @desc 锁定订单
     * @param array $params
     * @param array $memberInfo
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function withdrawLocking($params, $memberInfo) {
        $withdrawInfo = App::model('UserWithdraw')
            ->where('uw_withdraw_id', '=', $params['id'])
            ->find();
    
        //判断订单信息是否存在
        if(!$withdrawInfo) {
            $this->errorCode = EC_AD_USER_WITHDRAW_NOT_EXIST;
            return false;
        }
        
        //判断是否非法操作
        if($withdrawInfo['uw_status'] !== USER_WITHDRAW_STATUS_DEFAULT) {
            $this->errorCode = EC_ILLEGAL_OPERATION;
            return false;
        }
        
        $withdrawOrder = App::model('UserWithdraw')
            ->where('uw_withdraw_id', '=', $params['id'])
            ->update([
                'uw_member_id'     => $memberInfo['memberId'],
                'uw_status'        => USER_WITHDRAW_STATUS_LOCKING,
                'uw_locking_time'  => date('Y-m-d H:i:s'),
                'uw_modify_time'   => date('Y-m-d H:i:s')
            ]);
    
        if($withdrawOrder === false) {
            Db::commit();
            return true;
        }
    
        //添加行为日志
        App::model('common/BehaviorLog')->addLog([
            'controller' => 'Finance',
            'action'     => 'withdrawLocking',
            'message'    => '锁定提现订单ID:'.$params['id'],
            'username'   => $memberInfo['username'],
            'memberId'   => $memberInfo['memberId'],
        ]);
        
        return true;
    }
    
    /**
     * @desc 确认提现
     * @rule 确认提现解冻资金，扣除钱包金额
     * @param array $params
     * @param array $memberInfo
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function withdrawConfirm($params, $memberInfo) {
        $withdrawInfo = App::model('UserWithdraw')
                    ->where('uw_withdraw_id', '=', $params['id'])
                    ->find();
        
        //判断订单是否存在
        if(!$withdrawInfo) {
            $this->errorCode = EC_AD_USER_WITHDRAW_NOT_EXIST;
            return false;
        }
    
        //如果订单不是锁定状态就不能进行任何操作
        if($withdrawInfo['uw_status'] != USER_WITHDRAW_STATUS_LOCKING) {
            $this->errorCode = EC_ILLEGAL_OPERATION;
            return false;
        }
        
        //判断该订单操作人是否匹配
        if($memberInfo['memberId'] != $withdrawInfo['uw_member_id']) {
            $this->errorCode = EC_AD_USER_WITHDRAW_ALREADY_LOCKING;
            return false;
        }
        
        Db::startTrans();
        //修改提现订单状态
        $withdrawOrder = App::model('UserWithdraw')
                    ->where('uw_withdraw_id', '=', $params['id'])
                    ->update([
                        'uw_status'        => USER_WITHDRAW_STATUS_SUCCESS,
                        'uw_confirm_time'  => date('Y-m-d H:i:s'),
                        'uw_modify_time'   => date('Y-m-d H:i:s')
                    ]);
        
        //解冻资金
        $freezeResult = App::model('UserWallet')->unfreezeBalance($withdrawInfo['uw_freeze_id']);
        
        //扣除金额
        $balanceResult = App::model('UserWallet')
            ->decBalance($withdrawInfo['uw_user_id'], $withdrawInfo['uw_amount'], 'hs_user_withdraw:'.$withdrawInfo['uw_order_no'], '佣金提现');
        
        if($withdrawOrder === false || $freezeResult === false || $balanceResult === false) {
            Db::rollback();
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
    
        //添加行为日志
        App::model('common/BehaviorLog')->addLog([
            'controller' => 'Finance',
            'action'     => 'withdrawConfirm',
            'message'    => '确定提现订单ID:'.$params['id'],
            'username'   => $memberInfo['username'],
            'memberId'   => $memberInfo['memberId'],
        ]);
        
        Db::commit();
        return true;
    }
    
    /**
     * @desc 拒绝提现
     * @rule 拒绝提现之后解冻资金
     * @param array $params
     * @param array $memberInfo
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function withdrawRefuse($params, $memberInfo) {
        $withdrawInfo = App::model('UserWithdraw')
            ->where('uw_withdraw_id', '=', $params['id'])
            ->find();
        
        if(!$withdrawInfo) {
            $this->errorCode = EC_AD_USER_WITHDRAW_NOT_EXIST;
            return false;
        }
    
        //如果订单不是锁定状态就不能进行任何操作
        if($withdrawInfo['uw_status'] != USER_WITHDRAW_STATUS_LOCKING) {
            $this->errorCode = EC_ILLEGAL_OPERATION;
            return false;
        }
        
        //判断该订单操作人是否匹配
        if($memberInfo['memberId'] != $withdrawInfo['uw_member_id']) {
            $this->errorCode = EC_AD_USER_WITHDRAW_ALREADY_LOCKING;
            return false;
        }
    
        Db::startTrans();
        //修改提现订单状态
        $withdrawOrder = App::model('UserWithdraw')
            ->where('uw_withdraw_id', '=', $params['id'])
            ->update([
                'uw_status'        => USER_WITHDRAW_STATUS_FAIL,
                'uw_confirm_time'  => date('Y-m-d H:i:s'),
                'uw_modify_time'   => date('Y-m-d H:i:s')
            ]);
    
        //解冻资金
        $freezeResult = App::model('UserWallet')->unfreezeBalance($withdrawInfo['uw_freeze_id']);
        
        if($withdrawOrder === false || $freezeResult === false) {
            Db::rollback();
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
    
        //添加行为日志
        App::model('common/BehaviorLog')->addLog([
            'controller' => 'Finance',
            'action'     => 'withdrawRefuse',
            'message'    => '拒绝提现订单ID:'.$params['id'],
            'username'   => $memberInfo['username'],
            'memberId'   => $memberInfo['memberId'],
        ]);
        
        Db::commit();
        return true;
    }
    
    /**
     * @desc 用户钱包
     * @param $params
     * @return array
     * @throws \think\exception\DbException
     */
    public function userWallet($params) {
        $where = [];
        if($params['userName']) {
            $userId = App::model('User')
                ->where('user_phone', 'like', '%'.$params['userName'].'%')
                ->whereOr('user_email', 'like', '%'.$params['userName'].'%')
                ->value('user_id');
            if($userId) {
                $where[] = ['uw_user_id', '=', $userId];
            }
        }
        
        $list = App::model('UserWallet')
            ->where($where)
            ->order('uw_balance', 'desc')
            ->paginate($params['pageSize'], false, ['query' => request()->param()]);
        
        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = output_format($list['data'], 'uw');
            
            $userIds = array_unique(array_column($list, 'userId'));
            $userInfo = App::model('User')
                ->where('user_id', 'in', $userIds)
                ->column('user_phone,user_email', 'user_id');
            
            foreach ($list as $key => $value) {
                $list[$key]['availableBalance'] =  round($value['balance'] - $value['freezeBalance'], 2);
                $list[$key]['balance'] =  round($value['balance'], 2);
                $list[$key]['freezeBalance'] =  round($value['freezeBalance'], 2);
                $list[$key]['userName'] = $userInfo[$value['userId']]['user_phone'] ?: $userInfo[$value['userId']]['user_email'];
            }
        }
  
        return [
            'list'         => $list,
            'params'       => $params,
            'pagination'   => $pagination
        ];
    }
    
    /**
     * @desc 用户冻结记录
     * @param $params
     * @return array
     * @throws \think\exception\DbException
     */
    public function freezeRecord($params) {
        $list = App::model('FreezeRecord')
            ->where('ar_wallet_id', '=', $params['id'])
            ->order('ar_status desc,ar_freeze_id desc')
            ->paginate($params['pageSize'], false, ['query' => request()->param()]);
        
        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = output_format($list['data'], 'ar');
            foreach ($list as $key => $value) {
                $list[$key]['amount'] =  round($value['amount']);
            }
        }
        
        return [
            'list'         => $list,
            'params'       => $params,
            'pagination'   => $pagination
        ];
    }
    
    /**
     * @desc 金流记录
     * @param $params
     * @return array
     * @throws \think\exception\DbException
     */
    public function accountRecord($params) {
        $list = App::model('AccountRecord')
            ->where('ar_from_user_id', '=', $params['id'])
            ->whereOr('ar_to_user_id', '=', $params['id'])
            ->order('ar_transfer_id desc')
            ->paginate($params['pageSize'], false, ['query' => request()->param()]);
        
        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = output_format($list['data'], 'ar');
            
            $fromUserIds = array_column($list, 'fromUserId');
            $toUserIds   = array_column($list, 'toUserId');
            $userIds = array_unique(array_merge($fromUserIds, $toUserIds));
    
            $userInfo = App::model('User')
                ->where('user_id', 'in', $userIds)
                ->column('user_phone,user_email', 'user_id');
            
            foreach ($list as $key => $value) {
                //出账用户
                if($value['fromUserId'] > 0) {
                    $list[$key]['amount']       = round(0 - $value['amount']);
                    $list[$key]['fromUserName'] = $userInfo[$value['fromUserId']]['user_phone'] ?: $userInfo[$value['fromUserId']]['user_email'];
                }else{
                    $list[$key]['amount']       = round($value['amount']);
                    $list[$key]['fromUserName'] = '系统';
                }
                
                //入账用户
                if($value['toUserId'] > 0) {
                    $list[$key]['toUserName'] = $userInfo[$value['toUserId']]['user_phone'] ?: $userInfo[$value['toUserId']]['user_email'];
                }else{
                    $list[$key]['toUserName'] = '系统';
                }
                
                $list[$key]['beforeAmount'] = round($value['beforeAmount']);
                $list[$key]['afterAmount']  = round($value['afterAmount']);
            }
        }

        return [
            'list'         => $list,
            'params'       => $params,
            'pagination'   => $pagination
        ];
    }
}